<template>
    <el-row :gutter="2">
        <el-col :col="24" style="display: flex;justify-content: space-between; margin-bottom: 10px;">
            <el-space :size="2" wrap>
                <el-input v-model="search" placeholder="搜索" style="max-width: 300px;" />
                <el-button :icon="Search" @click="SearchHandler" plain />
            </el-space>
            <el-space wrap>
                <el-button :icon="Plus" @click="CreateDialog" plain round />
                <el-button :icon="Refresh" @click="RefreshTable" plain round />
            </el-space>
        </el-col>
        <el-col :span="24">
            <el-table :data="TableData" max-height="68vh" v-loading="loading"
                :header-cell-style="{ background: '#f4f6f8' }" :rules="rules" ref="RulesFormRef">
                <el-table-column type="expand">
                    <template #default="props">
                        <div style="padding: 20px;">
                            <el-descriptions title="详细信息" :column="2" direction="vertical">
                                <el-descriptions-item label="角色形象" :span="2">
                                    <el-image class="roles_avatar"
                                        :src="props.row.avatar ? props.row.avatar : 'https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg'"
                                        fit="fill">
                                        <template #error>
                                            <div class="image-slot">
                                                <el-icon><icon-picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </el-descriptions-item>
                                <el-descriptions-item label="译名">
                                    <h3>{{ props.row.c_name }}</h3>
                                </el-descriptions-item>
                                <el-descriptions-item label="原名">
                                    <h3>{{ props.row.rolename }}</h3>
                                </el-descriptions-item>
                                <el-descriptions-item label="简介" :span="2">{{ props.row.intro }}</el-descriptions-item>
                                <el-descriptions-item :span="2">
                                    <el-divider content-position="left">
                                        <h3>所属作品</h3>
                                    </el-divider>
                                </el-descriptions-item>
                                <el-descriptions-item>
                                    <el-space :size="10" wrap>
                                        <Card :url="props.row.cover"
                                            :name="props.row.production ? props.row.production : props.row.animename" />
                                    </el-space>
                                </el-descriptions-item>
                            </el-descriptions>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="角色名" :header-cell-class-name="'custom-header'">
                    <template #default="{ row }">
                        <el-text truncated>
                            {{ row.c_name }}
                        </el-text>
                    </template>
                </el-table-column>
                <el-table-column label="性别" prop="gender" width="60" :header-cell-class-name="'custom-header'" />
                <el-table-column label="年龄" prop="age" width="60" :header-cell-class-name="'custom-header'" />
                <el-table-column label="种族" prop="race" :header-cell-class-name="'custom-header'" />
                <el-table-column label="分类" width="160" align="center" :header-cell-class-name="'custom-header'">
                    <template #default="{ row }">
                        <el-tag>
                            {{ row.types }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建人" prop="creator" width="200" align="center"
                    :header-cell-class-name="'custom-header'" />
                <el-table-column label="创建时间" prop="create" width="160" align="center"
                    :header-cell-class-name="'custom-header'" />
                <el-table-column label="操作" width="300" fixed="right" align="center"
                    :header-cell-class-name="'custom-header'">
                    <template #default="{ row }">
                        <el-space :size="10" wrap>
                            <el-switch v-model="row.is_show" inline-prompt active-text="展示" inactive-text="隐藏"
                                :active-value="0" :inactive-value="1" :active-action-icon="View"
                                :inactive-action-icon="Hide"
                                style="--el-switch-on-color:  #13ce66; --el-switch-off-color: #ff4949"
                                :loading="loadingSwitch[row.id]" :before-change="() => beforeChange(row)" />
                            <el-button type="warning" :icon="Edit" @click="UpdateDialog(row)" link>修改</el-button>
                            <el-button type="danger" :icon="Delete" @click="SoftDelHandler(row)" link>删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty description="暂无数据" />
                </template>
            </el-table>
        </el-col>
        <el-col :span="24">
            <el-pagination v-model:currentPage="currentPage" :page-sizes="[20, 40, 80, 100]"
                v-model:page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalItems"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" hide-on-single-page
                class="pagination" />
        </el-col>

        <el-dialog v-model="CreateDialogForm" width="30%" title="新增词条">
            <el-form :model="form" :rules="rules" label-width="auto" ref="RulesFormRef">
                <el-form-item label="角色名" prop="rolename">
                    <el-input v-model="form.rolename" clearable required />
                </el-form-item>
                <el-form-item label="中文名" prop="c_name">
                    <el-input v-model="form.c_name" clearable required />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname" clearable required />
                </el-form-item>
                <el-space wrap>
                    <el-form-item label="种族" prop="race">
                        <el-input v-model="form.race" style="width: 200px;" clearable required />
                    </el-form-item>
                    <el-form-item label="年龄" prop="age">
                        <el-input-number v-model="form.age" :min="0" />
                    </el-form-item>
                </el-space>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio :label="0">男</el-radio>
                        <el-radio :label="1">女</el-radio>
                        <el-radio :label="2">未知</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="简介" prop="intro">
                    <el-input v-model="form.intro" :rows="4" maxlength="1000" type="textarea" show-word-limit
                        required />
                </el-form-item>
                <el-form-item label="分类" prop="types">
                    <el-radio-group v-model="form.types">
                        <el-radio :label="0">番剧</el-radio>
                        <el-radio :label="1">漫画</el-radio>
                        <el-radio :label="2">Galgame</el-radio>
                        <el-radio :label="3">小说</el-radio>
                    </el-radio-group>
                </el-form-item>
                <span class="dialog-footer">
                    <el-button @click="CancelCreateDialog(RulesFormRef)">取消</el-button>
                    <el-button type="primary" @click="createHandler(RulesFormRef)">
                        创建词条
                    </el-button>
                </span>
            </el-form>
        </el-dialog>

        <el-dialog v-model="UpdateDialogForm" width="30%" title="修改词条">
            <el-form :model="updateRows" :rules="rules" label-width="auto" ref="RulesFormRef">
                <el-form-item label="角色名" prop="rolename">
                    <el-input v-model="updateRows.rolename" clearable required />
                </el-form-item>
                <el-form-item label="中文名" prop="c_name">
                    <el-input v-model="updateRows.c_name" clearable required />
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="updateRows.nickname" clearable required />
                </el-form-item>
                <el-space wrap>
                    <el-form-item label="种族" prop="race">
                        <el-input v-model="updateRows.race" style="width: 200px;" clearable required />
                    </el-form-item>
                    <el-form-item label="年龄" prop="age">
                        <el-input-number v-model="updateRows.age" :min="0" />
                    </el-form-item>
                </el-space>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="updateRows.gender">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                        <el-radio label="未知"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="简介" prop="intro">
                    <el-input v-model="updateRows.intro" :rows="4" maxlength="1000" type="textarea" show-word-limit
                        required />
                </el-form-item>
                <el-form-item label="分类" prop="types">
                    <el-radio-group v-model="updateRows.types">
                        <el-radio label="番剧"></el-radio>
                        <el-radio label="漫画"></el-radio>
                        <el-radio label="Galgame"></el-radio>
                        <el-radio label="小说"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <span class="dialog-footer">
                    <el-button @click="CancelUpdateDialog(RulesFormRef)">取消</el-button>
                    <el-button type="primary" @click="UpdateHandler(RulesFormRef)">
                        修改词条
                    </el-button>
                </span>
            </el-form>
        </el-dialog>
    </el-row>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { ElSpace, ElDescriptions, ElText, ElInput, ElDivider, ElTag, ElButton, ElSwitch, ElDescriptionsItem, ElRow, ElCol, ElTable, ElTableColumn, ElEmpty, ElPagination, ElDialog } from 'element-plus';
import { Edit, Plus, Delete, Refresh, Search, Picture as IconPicture, View, Hide } from '@element-plus/icons-vue';
import { Info, Add, SearchRolesInfo, IsShow, SoftDel, Update } from '@/Apis/modules/roles';
import RolesStore from '@/stores/modules/RolesStore'

// 获取数据
onMounted(async () => await GetRolesInfo());

const store = RolesStore();
const search = ref('');
const RulesFormRef = ref();
const loading = ref(false)        // 懒加载赋值
const currentPage = ref(1);       // 当前页码
const pageSize = ref(20);         // 每页显示的数据条
const totalItems = ref(0);        // 总数据条数
// 分页
const handleSizeChange = (val) => {
    pageSize.value = val;         // 更新每页显示的数据条数
    currentPage.value = 1;        // 重置当前页码为第一页
}
const handleCurrentChange = (val) => {
    currentPage.value = val;      // 更新当前页码
}

// 动态渲染页面并筛选
const TableData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;

    return store.info.slice(start, end);
});

// 异步获取数据
const GetRolesInfo = async () => {
    loading.value = true;
    setTimeout(async () => {
        await Info();
        totalItems.value = store.info.length;
        loading.value = false;
    }, 1000)
}

// 刷新
const RefreshTable = async () => { await GetRolesInfo() };

// 对话框控制
const CreateDialogForm = ref(false);
const UpdateDialogForm = ref(false);
const CreateDialog = async () => {
    CreateDialogForm.value = true;
}
const UpdateDialog = async (row) => {
    updateRows.value = { ...row };
    UpdateDialogForm.value = true;
}

// 重置表单
const CancelCreateDialog = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    CreateDialogForm.value = false;
};
const CancelUpdateDialog = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    UpdateDialogForm.value = false;
};


// 验证规则
const rules = ref({
    rolename: [{ required: true, trigger: 'blur' }],
    c_name: [{ trigger: 'blur' }],
    nickname: [{ trigger: 'blur' }],
    race: [{ required: true, trigger: 'blur' }],
    gender: [{ trigger: 'blur' }],
    intro: [{ required: true, trigger: 'blur' }],
    types: [{ required: true, trigger: 'blur' }],
})

const form = reactive({
    rolename: '',
    c_name: '',
    nickname: '',
    race: '人类',
    age: 0,
    gender: 0,
    intro: '',
    types: 0,
})

const createHandler = async () => {
    await Add(form);
    await Info();
}

// 搜索
const SearchHandler = async () => {
    if (!search.value) return ElMessage.error("请输入关键词");
    await SearchRolesInfo(search.value);
}

// 是否展示
const loadingSwitch = reactive({});
const beforeChange = (row) => {
    const data = {
        id: row.id,
        is_show: row.is_show === 0 ? 1 : 0
    }
    loadingSwitch[row.id] = true;
    return new Promise(async (resolve) => {
        await IsShow(data).then(() => {
            setTimeout(async () => {
                loadingSwitch[row.id] = false
                return resolve(true);
            }, 1000)
        }).catch((error) => {
            loadingSwitch[row.id] = false;
            ElMessage.error('切换失败');
        })
    })
}

const updateRows = ref({
    rolename: null,
    c_name: null,
    nickname: null,
    race: null,
    age: null,
    gender: null,
    intro: null,
    types: null,
});

const UpdateHandler = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            console.log(updateRows.value);
            // await Update(updateRows.value);
            UpdateDialogForm.value = false
        } else {
            return ElMessage.error('验证未通过!')
        }
    })
}

const SoftDelHandler = async (row) => {
    const data = {
        id: row.id,
        is_delete: 1,
    };
    ElMessageBox.confirm(
        '是否删除该词条?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            // 发起删除请求
            await SoftDel(data).then(() => {
                const index = store.info.findIndex(item => item.id === data.id);
                if (index !== -1) {
                    store.info.splice(index, 1);
                }
            });
        })
        .catch(() => {
            return
        })
}
</script>

<style scoped>
.pagination {
    display: flex;
    justify-content: center;
    margin: 10px 0;
}

.roles_avatar {
    max-width: 500px;
    max-height: 500px;
    border-radius: 4px;
}

.dialog-footer {
    display: flex;
    justify-content: right;
}
</style>